package com.starhub.engine.document.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.extractor.XSSFExcelExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.ss.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import lombok.extern.slf4j.Slf4j;

import com.alibaba.fastjson2.JSONObject;
import com.starhub.engine.document.dto.DocContentDto;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
public class DocConvertUtil {

    public static DocContentDto extractHtml(InputStream inputStream, FileType fileType, Charset charset) {
        String content = "";
        JSONObject detail = new JSONObject();
        try {
            if (fileType == FileType.DOC) {
                // 处理DOC文件 - 保留原始格式
                HWPFDocument doc = new HWPFDocument(inputStream);
                content = convertDocToHtml(doc, charset, detail);
                doc.close();
            } else if (fileType == FileType.DOCX) {
                // 处理DOCX文件 - 保留原始格式
                XWPFDocument docx = new XWPFDocument(inputStream);
                content = convertDocxToHtml(docx, charset, detail);
                docx.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return DocContentDto.builder()
                .content(content)
                .detail(detail)
                .build();
    }

    /**
     * 将DOCX文档转换为HTML，使用div和span包裹，span中存放UUID
     */
    private static String convertDocxToHtml(XWPFDocument docx, Charset charset, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        // 处理段落
        for (XWPFParagraph paragraph : docx.getParagraphs()) {
            html.append(convertParagraphToHtml(paragraph, docx, detail));
        }

        // 处理表格
        for (XWPFTable table : docx.getTables()) {
            html.append(convertTableToHtml(table, docx, detail));
        }

        return html.toString();
    }

    /** 将DOCX段落转换为HTML，使用div包裹，最多一层div */
    private static String convertParagraphToHtml(XWPFParagraph paragraph, XWPFDocument docx, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        String alignment = getParagraphAlignment(paragraph.getAlignment());
        Integer beforeTwips = paragraph.getSpacingBefore();
        Integer afterTwips = paragraph.getSpacingAfter();
        double spacingBetween = paragraph.getSpacingBetween();
        Integer firstLineTwips = paragraph.getIndentationFirstLine();
        Integer indentLeftTwips = paragraph.getIndentationLeft();
        Integer indentRightTwips = paragraph.getIndentationRight();

        // 构建段落样式
        StringBuilder paragraphStyle = new StringBuilder();

        // 段落间距
        if (beforeTwips != null && beforeTwips > 0) {
            paragraphStyle.append("margin-top: ").append(twipsToPx(beforeTwips)).append("px; ");
        }
        if (afterTwips != null && afterTwips > 0) {
            paragraphStyle.append("margin-bottom: ").append(twipsToPx(afterTwips)).append("px; ");
        }

        // 对齐方式
        paragraphStyle.append("text-align: ").append(alignment).append("; ");

        // 行高
        if (spacingBetween > 0) {
            // 将行高转换为更合理的值
            double lineHeight = Math.max(1.0, Math.min(3.0, spacingBetween / 240.0));
            paragraphStyle.append("line-height: ").append(lineHeight).append("; ");
        } else {
            paragraphStyle.append("line-height: 1.5; ");
        }

        // 首行缩进
        if (firstLineTwips != null && firstLineTwips != 0) {
            paragraphStyle.append("text-indent: ").append(twipsToPx(firstLineTwips)).append("px; ");
        }

        // 左缩进
        if (indentLeftTwips != null && indentLeftTwips != 0) {
            paragraphStyle.append("margin-left: ").append(twipsToPx(indentLeftTwips)).append("px; ");
        }

        // 右缩进
        if (indentRightTwips != null && indentRightTwips != 0) {
            paragraphStyle.append("margin-right: ").append(twipsToPx(indentRightTwips)).append("px; ");
        }

        // 添加默认样式
        paragraphStyle.append("margin: 0; padding: 0; ");

        html.append("<div style=\"").append(paragraphStyle).append("\">");

        for (XWPFRun run : paragraph.getRuns()) {
            html.append(convertRunToHtml(run, docx, detail));
        }

        html.append("</div>");
        return html.toString();
    }

    /** 将DOCX运行（带格式的文本）转换为HTML，span中存放UUID */
    private static String convertRunToHtml(XWPFRun run, XWPFDocument docx, JSONObject detail) {
        StringBuilder html = new StringBuilder();

        // 首先处理图片
        try {
            if (run.getEmbeddedPictures() != null && !run.getEmbeddedPictures().isEmpty()) {
                run.getEmbeddedPictures().forEach(pic -> {
                    try {
                        byte[] data = pic.getPictureData().getData();
                        String mime = pic.getPictureData().getPackagePart().getContentType();
                        String base64 = Base64.getEncoder().encodeToString(data);
                        html.append("<img style=\"max-width:100%; height:auto;\" src=\"data:")
                                .append(mime).append(";base64,").append(base64).append("\"/>");
                    } catch (Exception ignore) {
                    }
                });
            }
        } catch (Exception ignore) {
        }

        // 获取文本内容
        String text = run.getText(0);
        if (text == null || text.isEmpty()) {
            return html.toString();
        }

        // 处理换行符，使用<br>标签
        text = text.replace("\n", "<br>");

        // 生成UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 构建样式
        Map<String, String> styleMap = new HashMap<>();
        String fontFamily = run.getFontFamily();
        if (fontFamily != null && !fontFamily.isEmpty()) {
            // 优化字体族映射，确保更好的显示效果
            String mappedFont = mapFontFamily(fontFamily);
            styleMap.put("font-family", "'" + mappedFont + "', " + getFallbackFonts(mappedFont));
        } else {
            // 默认字体
            styleMap.put("font-family", "'Microsoft YaHei', 'SimSun', 'Arial', sans-serif");
        }

        // 字体大小
        int fontSize = getFontSizeSafely(run);
        if (fontSize > 0) {
            // 智能转换字体大小单位
            double fontSizeInPt;

            // 根据字体大小范围智能判断单位
            if (fontSize >= 200) {
                // 如果字体大小很大，可能是半磅单位
                fontSizeInPt = fontSize / 2.0;
            } else if (fontSize >= 100) {
                // 如果字体大小在100-200之间，可能是半磅单位
                fontSizeInPt = fontSize / 2.0;
            } else if (fontSize >= 20) {
                // 如果字体大小在20-100之间，可能是磅单位
                fontSizeInPt = fontSize;
            } else if (fontSize >= 8) {
                // 如果字体大小在8-20之间，可能是磅单位
                fontSizeInPt = fontSize;
            } else {
                // 如果字体大小很小，可能是磅单位但需要调整
                fontSizeInPt = Math.max(8.0, fontSize);
            }

            // 限制字体大小范围，避免过大或过小
            fontSizeInPt = Math.max(8.0, Math.min(72.0, fontSizeInPt));

            // 格式化字体大小，保留一位小数
            String formattedSize = String.format("%.1f", fontSizeInPt);
            styleMap.put("font-size", formattedSize + "pt");

        } else {
            // 设置默认字体大小
            styleMap.put("font-size", "12pt");
        }

        if (run.isBold()) {
            styleMap.put("font-weight", "bold");
        }
        if (run.isItalic()) {
            styleMap.put("font-style", "italic");
        }
        if (run.isStrikeThrough() || run.isStrike()) {
            styleMap.put("text-decoration", "line-through");
        }
        if (run.getUnderline() != UnderlinePatterns.NONE) {
            styleMap.put("text-decoration", "underline");
        }

        // 处理文字颜色
        String color = run.getColor();
        if (color != null && !color.isEmpty()) {
            String processedColor = processColor(color);
            if (processedColor != null) {
                styleMap.put("color", processedColor);
            }
        }

        // 处理高亮色
        Object highlightColor = null;
        try {
            highlightColor = run.getTextHightlightColor();
        } catch (Throwable ignore) {
        }

        if (highlightColor != null) {
            String hc = highlightColor.toString().toLowerCase();
            if (!"none".equals(hc) && !"auto".equals(hc) && !"".equals(hc)) {
                String bg = getHighlightColor(hc);
                if (bg != null) {
                    styleMap.put("background-color", bg);
                }
            }
        }

        // 将内容和样式存储到映射中
        Map<String, Object> contentData = new HashMap<>();
        contentData.put("content", text);
        contentData.put("style", styleMap);
        JSONObject jo = new JSONObject(contentData);
        detail.put(uuid, jo);
        //contentMap.put(uuid, jo);

        // 输出span标签，包含UUID
        html.append("<span>").append(uuid).append("-").append("</span>");

        return html.toString();
    }

     /** 将DOCX表格转换为HTML，使用div和span包裹 */
     private static String convertTableToHtml(XWPFTable table, XWPFDocument docx, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        
        // 获取表格样式
        StringBuilder tableStyle = new StringBuilder();
        tableStyle.append("border-collapse: collapse; ");
        tableStyle.append("width: 100%; ");
        tableStyle.append("margin: 15px 0; ");
        tableStyle.append("border: 1px solid #ddd; ");
        
        html.append("<div style=\"").append(tableStyle).append("\">");
        html.append("<table style=\"border-collapse: collapse; width: 100%; border: 1px solid #ddd;\">\n");
        
        for (XWPFTableRow row : table.getRows()) {
            html.append("<tr>\n");
            for (XWPFTableCell cell : row.getTableCells()) {
                html.append(convertTableCellToHtml(cell, docx, detail));
            }
            html.append("</tr>\n");
        }
        html.append("</table>");
        html.append("</div>");
        return html.toString();
    }

    /** 将DOCX表格单元格转换为HTML，使用div和span包裹 */
    private static String convertTableCellToHtml(XWPFTableCell cell, XWPFDocument docx, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        CTTc ctTc = cell.getCTTc();
        StringBuilder cellStyle = new StringBuilder();
        
        // 基础单元格样式
        cellStyle.append("border: 1px solid #ddd; ");
        cellStyle.append("padding: 8px 12px; ");
        cellStyle.append("vertical-align: top; ");
        cellStyle.append("text-align: left; ");
        
        if (ctTc != null && ctTc.getTcPr() != null) {
            CTTcPr tcPr = ctTc.getTcPr();
            
            // 处理单元格边框
            if (tcPr.getTcBorders() != null) {
                // 可以根据具体边框设置更精确的样式
                cellStyle.append("border: 1px solid #000; ");
            }
            
            // 处理单元格背景色
            if (tcPr.getShd() != null && tcPr.getShd().getFill() != null) {
                Object fillColor = tcPr.getShd().getFill();
                if (fillColor != null) {
                    String color = fillColor.toString();
                    // 验证颜色值
                    if (color.matches("^[0-9A-Fa-f]{6}$")) {
                        cellStyle.append("background-color: #").append(color).append("; ");
                    } else if (color.startsWith("#")) {
                        cellStyle.append("background-color: ").append(color).append("; ");
                    }
                }
            }
            
            // 处理单元格宽度
            if (tcPr.getTcW() != null) {
                try {
                    Object widthObj = tcPr.getTcW().getW();
                    if (widthObj != null) {
                        int width = Integer.parseInt(widthObj.toString());
                        if (width > 0) {
                            cellStyle.append("width: ").append(width).append("px; ");
                        }
                    }
                } catch (Exception e) {
                    // 忽略异常
                }
            }
        }
        
        html.append("<td style=\"").append(cellStyle).append("\">\n");
        
        // 处理单元格内容，使用div包裹
        html.append("<div>");
        for (XWPFParagraph paragraph : cell.getParagraphs()) {
            html.append(convertParagraphToHtml(paragraph, docx, detail));
        }
        html.append("</div>");
        
        html.append("</td>");
        return html.toString();
    }

    /**
     * 获取段落对齐方式作为CSS值
     */
    private static String getParagraphAlignment(ParagraphAlignment alignment) {
        if (alignment == null) return "left";
        
        switch (alignment) {
            case LEFT: return "left";
            case CENTER: return "center";
            case RIGHT: return "right";
            case BOTH: return "justify";
            default: return "left";
        }
    }

    /**
     * 将twips转换为像素，使用更准确的转换比例
     */
    private static int twipsToPx(int twips) {
        if (twips <= 0) return 0;
        // 1 twip = 1/20 point, 1 point = 1.333333 pixels (96 DPI)
        // 所以 1 twip = 1/20 * 1.333333 = 0.0666667 pixels
        return Math.round(twips * 0.0666667f);
    }

    /**
     * 映射字体族名称，确保更好的兼容性
     */
    private static String mapFontFamily(String originalFont) {
        if (originalFont == null) return "Microsoft YaHei";
        
        String font = originalFont.toLowerCase();
        if (font.contains("宋体") || font.contains("simsun")) {
            return "SimSun";
        } else if (font.contains("黑体") || font.contains("simhei")) {
            return "SimHei";
        } else if (font.contains("微软雅黑") || font.contains("microsoft yahei")) {
            return "Microsoft YaHei";
        } else if (font.contains("楷体") || font.contains("kaiti")) {
            return "KaiTi";
        } else if (font.contains("仿宋") || font.contains("fangsong")) {
            return "FangSong";
        } else if (font.contains("arial")) {
            return "Arial";
        } else if (font.contains("times") || font.contains("times new roman")) {
            return "Times New Roman";
        } else if (font.contains("calibri")) {
            return "Calibri";
        } else {
            return originalFont;
        }
    }

    /**
     * 获取字体族的后备字体
     */
    private static String getFallbackFonts(String primaryFont) {
        if (primaryFont.contains("SimSun") || primaryFont.contains("SimHei") || 
            primaryFont.contains("Microsoft YaHei") || primaryFont.contains("KaiTi") || 
            primaryFont.contains("FangSong")) {
            return "'SimSun', 'Arial', sans-serif";
        } else {
            return "'Microsoft YaHei', 'SimSun', 'Arial', sans-serif";
        }
    }

    /**
     * 安全的字体大小获取方法，避免兼容性问题
     */
    private static int getFontSizeSafely(XWPFRun run) {
        if (run == null) return -1;
        
        // 方法1: 尝试直接获取
        try {
            int size = run.getFontSize();
            if (size > 0) return size;
        } catch (Exception e) {
            // 忽略异常
        }
        
        // 方法2: 尝试从字体名称推断
        try {
            String fontFamily = run.getFontFamily();
            if (fontFamily != null && !fontFamily.isEmpty()) {
                return getDefaultFontSize(fontFamily);
            }
        } catch (Exception e) {
            // 忽略异常
        }
        
        // 方法3: 返回默认值
        return 12;
    }


    /**
     * 处理颜色值，确保格式正确
     */
    private static String processColor(String color) {
        if (color == null || color.isEmpty()) {
            return null;
        }
        
        // 移除空格
        color = color.trim();
        
        // 如果已经是有效的十六进制颜色
        if (color.matches("^#[0-9A-Fa-f]{6}$")) {
            return color;
        }
        
        // 如果是6位十六进制数字，添加#
        if (color.matches("^[0-9A-Fa-f]{6}$")) {
            return "#" + color;
        }
        
        // 如果是3位十六进制数字，扩展为6位
        if (color.matches("^[0-9A-Fa-f]{3}$")) {
            StringBuilder expanded = new StringBuilder("#");
            for (char c : color.toCharArray()) {
                expanded.append(c).append(c);
            }
            return expanded.toString();
        }
        
        // 处理预定义颜色名称
        String lowerColor = color.toLowerCase();
        switch (lowerColor) {
            case "black": return "#000000";
            case "white": return "#FFFFFF";
            case "red": return "#FF0000";
            case "green": return "#00FF00";
            case "blue": return "#0000FF";
            case "yellow": return "#FFFF00";
            case "cyan": return "#00FFFF";
            case "magenta": return "#FF00FF";
            case "gray": case "grey": return "#808080";
            case "silver": return "#C0C0C0";
            case "maroon": return "#800000";
            case "olive": return "#808000";
            case "navy": return "#000080";
            case "purple": return "#800080";
            case "teal": return "#008080";
            case "lime": return "#00FF00";
            case "fuchsia": return "#FF00FF";
            case "aqua": return "#00FFFF";
            default: return null;
        }
    }

    /**
     * 获取高亮色对应的背景色
     */
    private static String getHighlightColor(String highlightType) {
        if (highlightType == null) return null;
        
        switch (highlightType.toLowerCase()) {
            case "yellow": return "#FFFF00";
            case "green": return "#00FF00";
            case "cyan": return "#00FFFF";
            case "magenta": return "#FF00FF";
            case "blue": return "#0000FF";
            case "red": return "#FF0000";
            case "darkyellow": case "dark_yellow": return "#999900";
            case "darkblue": case "dark_blue": return "#000080";
            case "darkcyan": case "dark_cyan": return "#008080";
            case "darkgreen": case "dark_green": return "#008000";
            case "darkmagenta": case "dark_magenta": return "#800080";
            case "darkred": case "dark_red": return "#800000";
            case "lightgray": case "light_gray": return "#D3D3D3";
            case "lightyellow": case "light_yellow": return "#FFFFE0";
            case "lightgreen": case "light_green": return "#90EE90";
            case "lightblue": case "light_blue": return "#ADD8E6";
            case "lightcyan": case "light_cyan": return "#E0FFFF";
            case "lightmagenta": case "light_magenta": return "#FFE0FF";
            case "lightred": case "light_red": return "#FFB6C1";
            default: return null;
        }
    }

    /**
     * 根据字体族获取默认字体大小
     */
    private static int getDefaultFontSize(String fontFamily) {
        if (fontFamily == null) return 12;
        
        String font = fontFamily.toLowerCase();
        if (font.contains("宋体") || font.contains("simsun")) {
            return 12;
        } else if (font.contains("黑体") || font.contains("simhei")) {
            return 14;
        } else if (font.contains("微软雅黑") || font.contains("microsoft yahei")) {
            return 12;
        } else if (font.contains("楷体") || font.contains("kaiti")) {
            return 12;
        } else if (font.contains("仿宋") || font.contains("fangsong")) {
            return 12;
        } else if (font.contains("arial")) {
            return 11;
        } else if (font.contains("times") || font.contains("times new roman")) {
            return 12;
        } else if (font.contains("calibri")) {
            return 11;
        } else {
            return 12; // 默认字体大小
        }
    }

    /**
     * 将DOC文档转换为HTML，使用div和span包裹，span中存放UUID，保持原始样式
     */
    private static String convertDocToHtml(HWPFDocument doc, Charset charset, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        
        try {
            // 获取文档范围
            org.apache.poi.hwpf.usermodel.Range range = doc.getRange();
            
            // 遍历段落
            for (int i = 0; i < range.numParagraphs(); i++) {
                org.apache.poi.hwpf.usermodel.Paragraph paragraph = range.getParagraph(i);
                html.append(convertDocParagraphToHtml(paragraph, doc, detail));
            }

            // 处理表格 - 暂时跳过，因为HWPF API限制
            log.debug("HWPF表格处理暂时跳过，需要进一步研究API");
            
        } catch (Exception e) {
            log.warn("WordExtractor失败，使用基本HWPF API: {}", e.getMessage());
            // 如果WordExtractor失败，尝试使用基本的HWPF API
            html.append(convertDocToHtmlBasic(doc, detail));
        }
        
        return html.toString();
    }
    
    /** 将DOC段落转换为HTML，使用div包裹，保持原始样式 */
    private static String convertDocParagraphToHtml(org.apache.poi.hwpf.usermodel.Paragraph paragraph, HWPFDocument doc, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        
        // 获取段落对齐方式 - 使用默认值
        String alignment = "left"; // 默认左对齐
        
        // 获取段落间距和缩进信息 - 使用默认值
        int beforeSpacing = 0;
        int afterSpacing = 0;
        int firstLineIndent = 0;
        int leftIndent = 0;
        int rightIndent = 0;
        
        // 获取行高
        int lineSpacing = 0;

        // 构建段落样式
        StringBuilder paragraphStyle = new StringBuilder();

        // 段落间距
        if (beforeSpacing > 0) {
            paragraphStyle.append("margin-top: ").append(twipsToPx(beforeSpacing)).append("px; ");
        }
        if (afterSpacing > 0) {
            paragraphStyle.append("margin-bottom: ").append(twipsToPx(afterSpacing)).append("px; ");
        }

        // 对齐方式
        paragraphStyle.append("text-align: ").append(alignment).append("; ");

        // 行高
        if (lineSpacing > 0) {
            // 将行高转换为更合理的值
            double lineHeight = Math.max(1.0, Math.min(3.0, lineSpacing / 240.0));
            paragraphStyle.append("line-height: ").append(lineHeight).append("; ");
        } else {
            paragraphStyle.append("line-height: 1.5; ");
        }

        // 首行缩进
        if (firstLineIndent != 0) {
            paragraphStyle.append("text-indent: ").append(twipsToPx(firstLineIndent)).append("px; ");
        }

        // 左缩进
        if (leftIndent != 0) {
            paragraphStyle.append("margin-left: ").append(twipsToPx(leftIndent)).append("px; ");
        }

        // 右缩进
        if (rightIndent != 0) {
            paragraphStyle.append("margin-right: ").append(twipsToPx(rightIndent)).append("px; ");
        }

        // 添加默认样式
        paragraphStyle.append("margin: 0; padding: 0; ");

        html.append("<div style=\"").append(paragraphStyle).append("\">");

        // 处理段落中的字符运行 - 使用正确的方法
        try {
            for (int i = 0; i < paragraph.numCharacterRuns(); i++) {
                org.apache.poi.hwpf.usermodel.CharacterRun run = paragraph.getCharacterRun(i);
                html.append(convertDocRunToHtml(run, doc, detail));
            }
        } catch (Exception e) {
            log.debug("获取字符运行失败: {}", e.getMessage());
        }

        html.append("</div>");
        return html.toString();
    }

    /** 将DOC运行（带格式的文本）转换为HTML，span中存放UUID，保持原始样式 */
    private static String convertDocRunToHtml(org.apache.poi.hwpf.usermodel.CharacterRun run, HWPFDocument doc, JSONObject detail) {
        StringBuilder html = new StringBuilder();

        // 获取文本内容
        String text = run.text();
        if (text == null || text.isEmpty()) {
            return html.toString();
        }

        // 处理换行符，使用<br>标签
        text = text.replace("\n", "<br>");

        // 生成UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");

        // 构建样式 - 提取原始样式信息
        Map<String, String> styleMap = new HashMap<>();
        
        // 字体族
        String fontFamily = run.getFontName();
        if (fontFamily != null && !fontFamily.isEmpty()) {
            // 优化字体族映射，确保更好的显示效果
            String mappedFont = mapFontFamily(fontFamily);
            styleMap.put("font-family", "'" + mappedFont + "', " + getFallbackFonts(mappedFont));
        } else {
            // 默认字体
            styleMap.put("font-family", "'Microsoft YaHei', 'SimSun', 'Arial', sans-serif");
        }

        // 字体大小
        int fontSize = run.getFontSize();
        if (fontSize > 0) {
            // 智能转换字体大小单位
            double fontSizeInPt;

            // 根据字体大小范围智能判断单位
            if (fontSize >= 200) {
                // 如果字体大小很大，可能是半磅单位
                fontSizeInPt = fontSize / 2.0;
            } else if (fontSize >= 100) {
                // 如果字体大小在100-200之间，可能是半磅单位
                fontSizeInPt = fontSize / 2.0;
            } else if (fontSize >= 20) {
                // 如果字体大小在20-100之间，可能是磅单位
                fontSizeInPt = fontSize / 2.0;;
            } else if (fontSize >= 8) {
                // 如果字体大小在8-20之间，可能是磅单位
                fontSizeInPt = fontSize;
            } else {
                // 如果字体大小很小，可能是磅单位但需要调整
                fontSizeInPt = Math.max(8.0, fontSize);
            }

            // 限制字体大小范围，避免过大或过小
            fontSizeInPt = Math.max(8.0, Math.min(72.0, fontSizeInPt));

            // 格式化字体大小，保留一位小数
            String formattedSize = String.format("%.1f", fontSizeInPt);
            styleMap.put("font-size", formattedSize + "pt");

        } else {
            // 设置默认字体大小
            styleMap.put("font-size", "12pt");
        }

        // 字体样式
        if (run.isBold()) {
            styleMap.put("font-weight", "bold");
        }
        if (run.isItalic()) {
            styleMap.put("font-style", "italic");
        }
        
        // 删除线 - 由于HWPF API限制，暂时跳过
        // 下划线 - 由于HWPF API限制，暂时跳过
        // 文字颜色 - 由于HWPF API限制，暂时跳过
        // 高亮色 - 由于HWPF API限制，暂时跳过

        // 将内容和样式存储到映射中
        Map<String, Object> contentData = new HashMap<>();
        contentData.put("content", text);
        contentData.put("style", styleMap);
        JSONObject jo = new JSONObject(contentData);
        detail.put(uuid, jo);

        // 输出span标签，包含UUID
        html.append("<span>").append(uuid).append("-").append("</span>");

        return html.toString();
    }

    /** 将DOC表格转换为HTML，使用div和span包裹，保持原始样式 */
    private static String convertDocTableToHtml(org.apache.poi.hwpf.usermodel.Table table, HWPFDocument doc, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        
        // 获取表格样式
        StringBuilder tableStyle = new StringBuilder();
        tableStyle.append("border-collapse: collapse; ");
        tableStyle.append("width: 100%; ");
        tableStyle.append("margin: 15px 0; ");
        tableStyle.append("border: 1px solid #ddd; ");
        
        html.append("<div style=\"").append(tableStyle).append("\">");
        html.append("<table style=\"border-collapse: collapse; width: 100%; border: 1px solid #ddd;\">\n");
        
        // 遍历表格行
        for (int i = 0; i < table.numRows(); i++) {
            org.apache.poi.hwpf.usermodel.TableRow row = table.getRow(i);
            html.append("<tr>\n");
            
            // 遍历行中的单元格
            for (int j = 0; j < row.numCells(); j++) {
                org.apache.poi.hwpf.usermodel.TableCell cell = row.getCell(j);
                html.append(convertDocTableCellToHtml(cell, doc, detail));
            }
            html.append("</tr>\n");
        }
        html.append("</table>");
        html.append("</div>");
        return html.toString();
    }

    /** 将DOC表格单元格转换为HTML，使用div和span包裹，保持原始样式 */
    private static String convertDocTableCellToHtml(org.apache.poi.hwpf.usermodel.TableCell cell, HWPFDocument doc, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        StringBuilder cellStyle = new StringBuilder();
        
        // 基础单元格样式
        cellStyle.append("border: 1px solid #ddd; ");
        cellStyle.append("padding: 8px 12px; ");
        cellStyle.append("vertical-align: top; ");
        cellStyle.append("text-align: left; ");
        
        // 处理单元格宽度
        int cellWidth = cell.getWidth();
        if (cellWidth > 0) {
            cellStyle.append("width: ").append(twipsToPx(cellWidth)).append("px; ");
        }
        
        html.append("<td style=\"").append(cellStyle).append("\">\n");
        
        // 处理单元格内容，使用div包裹
        html.append("<div>");
        
        // 遍历单元格中的段落
        for (int i = 0; i < cell.numParagraphs(); i++) {
            org.apache.poi.hwpf.usermodel.Paragraph paragraph = cell.getParagraph(i);
            html.append(convertDocParagraphToHtml(paragraph, doc, detail));
        }
        
        html.append("</div>");
        html.append("</td>");
        return html.toString();
    }

    /**
     * 获取DOC段落对齐方式作为CSS值
     */
    private static String getDocParagraphAlignment(int justificationCode) {
        switch (justificationCode) {
            case 0: return "left";      // 左对齐
            case 1: return "center";    // 居中对齐
            case 2: return "right";     // 右对齐
            case 3: return "justify";   // 两端对齐
            default: return "left";
        }
    }

    /**
     * 将DOC颜色值转换为十六进制颜色
     */
    private static String convertDocColorToHex(int color) {
        if (color == 0) return null;
        
        // DOC颜色通常是BGR格式，需要转换为RGB
        int blue = (color >> 16) & 0xFF;
        int green = (color >> 8) & 0xFF;
        int red = color & 0xFF;
        
        return String.format("#%02X%02X%02X", red, green, blue);
    }

    /**
     * 获取DOC高亮色对应的背景色
     */
    private static String getDocHighlightColor(int highlightCode) {
        switch (highlightCode) {
            case 1: return "#FFFF00";  // 黄色
            case 2: return "#00FF00";  // 绿色
            case 3: return "#00FFFF";  // 青色
            case 4: return "#FF00FF";  // 洋红
            case 5: return "#0000FF";  // 蓝色
            case 6: return "#FF0000";  // 红色
            case 7: return "#999900";  // 深黄色
            case 8: return "#000080";  // 深蓝色
            case 9: return "#008080";  // 深青色
            case 10: return "#008000"; // 深绿色
            case 11: return "#800080"; // 深洋红
            case 12: return "#800000"; // 深红色
            case 13: return "#D3D3D3"; // 浅灰色
            case 14: return "#FFFFE0"; // 浅黄色
            case 15: return "#90EE90"; // 浅绿色
            case 16: return "#ADD8E6"; // 浅蓝色
            case 17: return "#E0FFFF"; // 浅青色
            case 18: return "#FFE0FF"; // 浅洋红
            case 19: return "#FFB6C1"; // 浅红色
            default: return null;
        }
    }

    /**
     * 使用基本HWPF API转换DOC文档（备选方案）
     */
    private static String convertDocToHtmlBasic(HWPFDocument doc, JSONObject detail) {
        StringBuilder html = new StringBuilder();
        
        try {
            // 获取文档范围
            org.apache.poi.hwpf.usermodel.Range range = doc.getRange();
            
            // 遍历段落
            for (int i = 0; i < range.numParagraphs(); i++) {
                org.apache.poi.hwpf.usermodel.Paragraph paragraph = range.getParagraph(i);
                String paragraphText = paragraph.text();
                
                if (paragraphText.trim().isEmpty()) {
                    continue;
                }
                
                html.append("<div style=\"margin: 10px 0; line-height: 1.5;\">");
                
                // 为每个段落生成UUID并存储内容
                String uuid = UUID.randomUUID().toString().replace("-", "");
                
                // 构建样式
                Map<String, String> styleMap = new HashMap<>();
                styleMap.put("font-family", "'Microsoft YaHei', 'SimSun', 'Arial', sans-serif");
                styleMap.put("font-size", "12pt");
                styleMap.put("line-height", "1.5");
                
                // 将内容和样式存储到映射中
                Map<String, Object> contentData = new HashMap<>();
                contentData.put("content", paragraphText.trim());
                contentData.put("style", styleMap);
                JSONObject jo = new JSONObject(contentData);
                detail.put(uuid, jo);
                
                // 输出span标签，包含UUID
                html.append("<span>").append(uuid).append("-").append("</span>");
                
                html.append("</div>");
            }
            
        } catch (Exception e) {
            // log.error("基本HWPF API也失败: {}", e.getMessage()); // Original code had this line commented out
            // 最后的备选方案：返回简单的文本
            html.append("<div style=\"margin: 10px 0; line-height: 1.5;\">");
            String uuid = UUID.randomUUID().toString().replace("-", "");
            
            Map<String, String> styleMap = new HashMap<>();
            styleMap.put("font-family", "'Microsoft YaHei', 'SimSun', 'Arial', sans-serif");
            styleMap.put("font-size", "12pt");
            styleMap.put("line-height", "1.5");
            
            Map<String, Object> contentData = new HashMap<>();
            contentData.put("content", "DOC文档内容提取失败");
            contentData.put("style", styleMap);
            JSONObject jo = new JSONObject(contentData);
            detail.put(uuid, jo);
            
            html.append("<span>").append(uuid).append("-").append("</span>");
            html.append("</div>");
        }
        
        return html.toString();
    }


}
